package cn.dinkevin.xui.util;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;

import org.xmlpull.v1.XmlPullParser;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 资源工具类
 * Created by chengpengfei on 2017/8/19.
 * Copyright ©2017 juziwl, All Rights Reserved.
 */

public final class ResourceUtil {

    private ResourceUtil(){}

    /**
     * 从XML文件读取内容
     * @param c
     * @param hashMapResId
     * @return
     */
    public static Map<String,String> getHashMapResource(Context c, int hashMapResId) {

        Map<String,String> map = new HashMap<>();
        XmlResourceParser parser = c.getResources().getXml(hashMapResId);
        String key = null, value = null;

        try {
            int eventType = parser.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_DOCUMENT) {
                    Log.d("utils","Start document");
                } else if (eventType == XmlPullParser.START_TAG) {
                    if (parser.getName().equals("map")) {
                        boolean isLinked = parser.getAttributeBooleanValue(null, "linked", false);
                        map = isLinked ? new LinkedHashMap<String, String>() : new HashMap<String, String>();
                    } else if (parser.getName().equals("entry")) {
                        key = parser.getAttributeValue(null, "key");
                        if (null == key) {
                            parser.close();
                            return map;
                        }
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if (parser.getName().equals("entry")) {
                        map.put(key, value);
                        key = null;
                        value = null;
                    }
                } else if (eventType == XmlPullParser.TEXT) {
                    if (null != key) {
                        value = parser.getText();
                    }
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
